
// This class handles the communication between the server and the client.
// It automatically handles key checks, so we don't have to do that at every
// request in the application ourselves.
var AjaxRequest = new Class({
	// On initialize, predefine some variables
	initialize: function(url)
	{
		this.url        = url;
		this.locked     = false;
		this.queue      = [];
		this.queueDone  = 0;
		
	}, // end function initialize
	
	// Unlock the AJAX request (this is triggered when an ajax request is done)
	unlock: function()
	{
		this.locked = false;
		
	}, // end function unlock
	
	// Lock the AJAX request (this is triggered when a new ajax request is send)
	lock: function()
	{
		this.locked = true;
		
	}, // end function lock
	
	// Check if the AJAX request is locked.
	isLocked: function()
	{
		return this.locked;
		
	}, // end function isLocked
	
	// Remove one ajax request from te queue
	clearQueue: function()
	{
		// If there is one queue ....
		if (this.queue.length > this.queueDone)
		{
			// Get the first one which we haven't done yet.
			var active = this.queue[this.queueDone];
			
			// Move the pointer of the queue one further.
			this.queueDone++;
			
			// Redo the request
			this.request(active['action'], active['keys'], active['values'], active['onDone'], active['loading'], active['typeLoading']);
			
		} // end if
		
	}, // end function
	
	// Add a request to the queue to avoid key conflicts.
	addQueue: function(action, keys, values, onDone, loading, typeLoading)
	{
		// Just add everything to an array.
		this.queue.extend(
			[{
				action: action,
				keys:   keys,
				values: values,
				onDone: onDone,
				loading: loading,
				typeLoading: typeLoading
			}]
		);
		
		return false;
		
	},
	
	// This function is triggered when something went wrong between the client and server.
	// Most change is that the server has done something wrong.. but we can't continue
	// as the request has failed.. so we're forced to log the user out and give a message.
	Server_error: function()
	{
		// Log out
		session_end();
		
		// Give a message
		alert('Something odd happened when communicating with you and the server. Please re-login.');
		
		return;
		
	},
	
	// Do a request!
	request: function(action, keys, values, onDone, loading, typeLoading)
	{
		// When no keys/values are specified, just make it an empty array
		if (keys   == null) keys   = [];
		if (values == null) values = [];
		
		// When no loading is specified, make it standard.
		if (typeLoading == null) typeLoading = 1;
		
		// If there is an lock, build up a queue.
		if (this.isLocked())
			this.addQueue(action, keys, values, onDone, loading, typeLoading);
		else
		{
			// Do we require a key already (if the user is logged in that is)
			if (chat.getClsSession().requiresKey())
			{
				// Add our key value
				keys.extend(['k']);
				values.extend([chat.getClsSession().getKey()]);
				
			} // end if
			
			// Possible show a loading screen
			if (loading == null)
				ShowLoading(null, typeLoading);
			else if(loading != false)
				ShowLoading(loading, typeLoading);
			
			// Extend the parameters with action etc.
			keys.extend(['action']);
			values.extend([action]);
			
			// Lock this class to prevent key conflicts.
			this.lock();
			
			// Generate the request
			var request = new XHR(
				{
					method: 'get',  // TODO: Make it a post.
					onSuccess: function(txt, xml) {
						
						// Unlock again. (but don't clear a queue).
						chat.getClsAjaxReq().unlock();
//						alert(txt);
						// Check the key if we required one.
						if (chat.getClsSession().requiresKey())
						{
							// Remove first line from the result
							var lines = txt.split("\n");
							
							// If the first line isn't an integer, or it's zero... 
							// something went realy wrong man!
							if (lines[0].toInt() != lines[0] || lines[0].toInt() == 0)
							{
								return chat.getClsAjaxReq().Server_error();
								
							} // end if
							
							// Save the new key that's on the first line.
							chat.getClsSession().setKey(lines[0]);
							
							// remove the first line
							txt = "";
							
							for (var i = 1; i < lines.length; i++)
								if (txt == "")
									txt = lines[i];
								else
									txt = txt + "\n" + lines[i];
							
						} // end if
						
						// Clear on piece of the queue
						chat.getClsAjaxReq().clearQueue();
						
						// Execute the data we got.
						if (onDone != null)
							onDone(txt);
						
						// Now, we're finally done loading.
						if (loading)
							HideLoading();
						
					} // end function event onSuccess
				}
			// Send the request.
			).send(this.url + "ajax.php?" + Object.toQueryString(values.associate(keys)), null);
			
		} // end else
		
	} // end function request
	
}); // end class ajaxRequest

// Yay, we've loaded the ajax request library!
cimport_loaded('core.AjaxRequest');